//! # 网关核心类型定义
//!
//! 定义网关系统的核心数据类型，提供统一的数据模型。

use axum::http::{HeaderMap, Method, StatusCode, Uri};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, SystemTime};

/// 网关请求对象
/// 
/// 封装HTTP请求的所有信息，提供统一的请求处理接口。
#[derive(Debug, Clone)]
pub struct GatewayRequest {
    /// 请求ID，用于链路追踪
    pub id: String,
    /// HTTP方法
    pub method: Method,
    /// 请求URI
    pub uri: Uri,
    /// 请求头
    pub headers: HeaderMap,
    /// 请求体
    pub body: Vec<u8>,
    /// 客户端IP地址
    pub client_ip: Option<String>,
    /// 请求时间戳
    pub timestamp: SystemTime,
    /// 目标服务名
    pub target_service: Option<String>,
    /// 请求路径（去除服务名后的路径）
    pub path: String,
    /// 查询参数
    pub query_params: HashMap<String, String>,
}

impl GatewayRequest {
    /// 创建新的网关请求
    pub fn new(method: Method, uri: Uri) -> Self {
        let id = format!("{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos());
        let path = uri.path().to_string();
        let query_params = Self::parse_query_params(&uri);
        
        Self {
            id,
            method,
            uri,
            headers: HeaderMap::new(),
            body: Vec::new(),
            client_ip: None,
            timestamp: SystemTime::now(),
            target_service: None,
            path,
            query_params,
        }
    }
    
    /// 解析查询参数
    fn parse_query_params(uri: &Uri) -> HashMap<String, String> {
        let mut params = HashMap::new();
        if let Some(query) = uri.query() {
            for pair in query.split('&') {
                if let Some((key, value)) = pair.split_once('=') {
                    params.insert(
                        key.to_string(),
                        value.to_string(),
                    );
                }
            }
        }
        params
    }
    
    /// 设置目标服务
    pub fn set_target_service(&mut self, service: String) {
        self.target_service = Some(service);
    }
    
    /// 设置客户端IP
    pub fn set_client_ip(&mut self, ip: String) {
        self.client_ip = Some(ip);
    }
    
    /// 添加请求头
    pub fn add_header(&mut self, name: &str, value: &str) {
        if let (Ok(header_name), Ok(header_value)) = (
            name.parse::<axum::http::HeaderName>(), 
            value.parse::<axum::http::HeaderValue>()
        ) {
            self.headers.insert(header_name, header_value);
        }
    }
    
    /// 设置请求体
    pub fn set_body(&mut self, body: Vec<u8>) {
        self.body = body;
    }
}

/// 网关响应对象
/// 
/// 封装HTTP响应的所有信息，提供统一的响应处理接口。
#[derive(Debug, Clone)]
pub struct GatewayResponse {
    /// 响应状态码
    pub status: StatusCode,
    /// 响应头
    pub headers: HeaderMap,
    /// 响应体
    pub body: Vec<u8>,
    /// 处理时间（毫秒）
    pub processing_time: u64,
    /// 响应时间戳
    pub timestamp: SystemTime,
    /// 处理的服务实例信息
    pub service_instance: Option<String>,
}

impl GatewayResponse {
    /// 创建新的网关响应
    pub fn new(status: StatusCode) -> Self {
        Self {
            status,
            headers: HeaderMap::new(),
            body: Vec::new(),
            processing_time: 0,
            timestamp: SystemTime::now(),
            service_instance: None,
        }
    }
    
    /// 创建成功响应
    pub fn ok() -> Self {
        Self::new(StatusCode::OK)
    }
    
    /// 创建错误响应
    pub fn error(status: StatusCode, message: &str) -> Self {
        let mut response = Self::new(status);
        response.body = message.as_bytes().to_vec();
        response.add_header("content-type", "text/plain");
        response
    }
    
    /// 添加响应头
    pub fn add_header(&mut self, name: &str, value: &str) {
        if let (Ok(header_name), Ok(header_value)) = (
            name.parse::<axum::http::HeaderName>(), 
            value.parse::<axum::http::HeaderValue>()
        ) {
            self.headers.insert(header_name, header_value);
        }
    }
    
    /// 设置响应体
    pub fn set_body(&mut self, body: Vec<u8>) {
        self.body = body;
    }
    
    /// 设置处理时间
    pub fn set_processing_time(&mut self, time: u64) {
        self.processing_time = time;
    }
    
    /// 设置服务实例信息
    pub fn set_service_instance(&mut self, instance: String) {
        self.service_instance = Some(instance);
    }
}

/// 网关处理上下文
/// 
/// 保存请求处理过程中的上下文信息，支持中间件间的数据传递。
#[derive(Debug, Clone)]
pub struct GatewayContext {
    /// 请求ID
    pub request_id: String,
    /// 认证信息
    pub auth_info: Option<AuthInfo>,
    /// 限流信息
    pub rate_limit_info: Option<RateLimitInfo>,
    /// 路由信息
    pub route_info: Option<RouteInfo>,
    /// 自定义属性
    pub attributes: HashMap<String, String>,
    /// 处理开始时间
    pub start_time: SystemTime,
}

impl GatewayContext {
    /// 创建新的网关上下文
    pub fn new(request_id: String) -> Self {
        Self {
            request_id,
            auth_info: None,
            rate_limit_info: None,
            route_info: None,
            attributes: HashMap::new(),
            start_time: SystemTime::now(),
        }
    }
    
    /// 设置认证信息
    pub fn set_auth_info(&mut self, auth_info: AuthInfo) {
        self.auth_info = Some(auth_info);
    }
    
    /// 设置限流信息
    pub fn set_rate_limit_info(&mut self, rate_limit_info: RateLimitInfo) {
        self.rate_limit_info = Some(rate_limit_info);
    }
    
    /// 设置路由信息
    pub fn set_route_info(&mut self, route_info: RouteInfo) {
        self.route_info = Some(route_info);
    }
    
    /// 添加自定义属性
    pub fn add_attribute(&mut self, key: String, value: String) {
        self.attributes.insert(key, value);
    }
    
    /// 获取自定义属性
    pub fn get_attribute(&self, key: &str) -> Option<&String> {
        self.attributes.get(key)
    }
    
    /// 计算处理时间
    pub fn elapsed_time(&self) -> Duration {
        SystemTime::now().duration_since(self.start_time).unwrap_or_default()
    }
}

/// 认证信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthInfo {
    /// 用户ID
    pub user_id: String,
    /// 用户名
    pub username: Option<String>,
    /// 角色列表
    pub roles: Vec<String>,
    /// 权限列表
    pub permissions: Vec<String>,
    /// 认证类型
    pub auth_type: String,
    /// 额外属性
    pub attributes: HashMap<String, String>,
}

/// 限流信息
#[derive(Debug, Clone)]
pub struct RateLimitInfo {
    /// 是否被限流
    pub limited: bool,
    /// 剩余配额
    pub remaining: u32,
    /// 配额重置时间
    pub reset_time: SystemTime,
    /// 限流规则ID
    pub rule_id: Option<String>,
}

/// 路由信息
#[derive(Debug, Clone)]
pub struct RouteInfo {
    /// 路由ID
    pub id: String,
    /// 目标服务
    pub target_service: String,
    /// 路径重写规则
    pub path_rewrite: Option<String>,
    /// 请求转换规则
    pub transform_rules: Vec<TransformRule>,
}

/// 转换规则
#[derive(Debug, Clone)]
pub struct TransformRule {
    /// 规则类型
    pub rule_type: TransformType,
    /// 源字段
    pub source: String,
    /// 目标字段
    pub target: String,
    /// 转换值
    pub value: Option<String>,
}

/// 转换类型
#[derive(Debug, Clone)]
pub enum TransformType {
    /// 添加请求头
    AddHeader,
    /// 移除请求头
    RemoveHeader,
    /// 修改请求头
    ModifyHeader,
    /// 路径重写
    PathRewrite,
    /// 查询参数添加
    AddQueryParam,
}

/// 网关统计指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GatewayMetrics {
    /// 总请求数
    pub total_requests: u64,
    /// 成功请求数
    pub successful_requests: u64,
    /// 失败请求数
    pub failed_requests: u64,
    /// 平均响应时间（毫秒）
    pub avg_response_time: f64,
    /// 当前活跃连接数
    pub active_connections: u32,
    /// 限流拒绝数
    pub rate_limited_requests: u64,
    /// 认证失败数
    pub auth_failed_requests: u64,
    /// 服务实例健康状态
    pub service_health: HashMap<String, bool>,
}